/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

package com.jjsoft.celularessuc.gco.rep;

/**
 *
 * @author javila
 */
import com.jjsoft.celularessuc.gco.util.MiModelo;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.TreeMap;
import javax.swing.JTable;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;

/**
 *
 * @author javila
 */
public class ExelGenerator {

    XSSFWorkbook workbook;

    public ExelGenerator() {
    }

    public void generateExcel() {
        workbook = new XSSFWorkbook();
    }

    public void WriteSheets(JTable tabla, String name) {
        XSSFSheet sheet = workbook.createSheet(name);
        //Map<String, Object[]> data = new TreeMap<String, Object[]>();
        MiModelo modelo=(MiModelo)tabla.getModel();
        String [] headers= new String[modelo.getColumnCount()];
        for(int i=0;i<modelo.getColumnCount();i++)
        {
            headers[i]=modelo.getColumnName(i);
        }
        List<Object[]> dataList = new ArrayList<Object[]>();
        dataList.add((Object[]) headers);
        
        for(int i=0;i<modelo.getRowCount();i++)
        {
            Object [] data = new Object[modelo.getColumnCount()];
            for(int j=0;j<modelo.getColumnCount();j++)
            {
                data[j]=modelo.getValueAt(i, j);
            }
            dataList.add(data);
        }

        int rownum = 0;
        for (Object[] data : dataList) {
            Row row = sheet.createRow(rownum++);
            Object[] objArr = data;
            int cellnum = 0;
            for (Object obj : objArr) {
                Cell cell = row.createCell(cellnum++);
                if (obj instanceof String) {
                    cell.setCellValue((String) obj);
                } else if (obj instanceof Integer) {
                    cell.setCellValue((Integer) obj);
                } else if (obj instanceof Double) {
                    cell.setCellValue((Double) obj);
                } else if (obj instanceof Date) {
                    cell.setCellValue((Date) obj);
                }
            }
        }
        
    }
    
  
    
    public void writeworkbook(String path) throws FileNotFoundException, IOException{
            //Write the workbook in file system
            FileOutputStream out = new FileOutputStream(new File(path));
            workbook.write(out);
            out.close();
        
    }

}